import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [searchTerm, setSearchTerm] = useState('');
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(0);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('/vocabulary', {
          params: {
            search_term:searchTerm,
            page,
            per_page: perPage,
          },
        });

        setData(response.data.items);
        setPage(response.data.page);
        setPerPage(response.data.per_page);
        setTotalItems(response.data.total_items);
        setTotalPages(response.data.total_pages);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [searchTerm, page, perPage]);

  const handleSearchTermChange = (event) => {
    setSearchTerm(event.target.value);
  };

  const handlePageChange = (newPage) => {
    setPage(newPage);
  };
  function handlePerPageChange(event) {
    setPerPage(parseInt(event.target.value));
  }

  return (
    <div className="App">
      <h1>Vocabulary Search</h1>
      <input
        type="text"
        placeholder="Search term"
        value={searchTerm}
        onChange={handleSearchTermChange}
      />
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Term</th>
            <th>Attribute </th>
            <th>Collocates</th>
            <th>Synonyms</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item) => (
            <tr key={item.id}>
              <td>{item.id}</td>
              <td>{item.term}</td>
              <td>{item.attr}</td>
              <td>{item.collocates}</td>
              <td>{item.synonyms}</td>
             </tr>
          ))}
        </tbody>
      </table>
      <div>
        <button onClick={() => handlePageChange(page - 1)} disabled={page === 1}>
          Previous
        </button>
        <button onClick={() => handlePageChange(page + 1)} disabled={page === totalPages}>
          Next
        </button>
      </div>
      <div>
        <p>Page index: {page} Total Pages: {totalPages}</p> 
        <div>
        Items per page: <input type="number" value={perPage} onChange={handlePerPageChange}  />
        <p>Total Items: {totalItems}</p>
      </div>
              
      </div>
    </div>
  );
}
export default App;
